<template>
  <el-drawer v-model="drawer2" :direction="direction" :width="800" :before-close="handleClose">
    <template #header>
      <h4 style="font-size: 16px; font-weight: 600">手动添加新闻</h4>
    </template>
    <template #default>
      <div class="form-container">
        <el-form ref="formRef" :model="newsForm" :rules="rules" label-position="top">
          <el-form-item v-show="false" prop="id">
            <el-input v-model="newsForm.id" placeholder="请输入"></el-input>
          </el-form-item>
          <!-- 新闻标题 -->
          <div class="form-item">
            <el-form-item label="新闻标题" prop="newsTitle" required>
              <el-input v-model="newsForm.newsTitle" placeholder="请输入"></el-input>
            </el-form-item>
          </div>

          <!-- 新闻标签 -->
          <div class="form-item">
            <el-form-item label="新闻标签" prop="classReal" required>
              <el-select v-model="newsForm.classReal" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in classList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>

          <!-- 新闻来源 -->
          <div class="form-item">
            <el-form-item label="新闻来源" prop="siteName">
              <el-input v-model="newsForm.siteName" placeholder="请输入"></el-input>
            </el-form-item>
          </div>

          <!-- 新闻网址 -->
          <div class="form-item">
            <el-form-item label="新闻网址" prop="sourceUrl">
              <el-input v-model="newsForm.sourceUrl" placeholder="请输入"></el-input>
            </el-form-item>
          </div>

          <!-- 新闻摘要 -->
          <div class="form-item">
            <el-form-item label="新闻摘要" prop="abstractReal" required>
              <el-input
                v-model="newsForm.abstractReal"
                type="textarea"
                :rows="4"
                placeholder="请输入新闻摘要"
              ></el-input>
              <div class="tips">建议200字以内</div>
            </el-form-item>
          </div>

          <!-- 新闻正文 -->
          <div class="form-item">
            <el-form-item label="正文内容" prop="markContent">
              <el-input
                v-model="newsForm.markContent"
                type="textarea"
                :rows="4"
                placeholder="请输入正文内容"
              ></el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div style="display: flex; justify-content: flex-end; gap: 10px">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick(formRef)">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { DrawerProps, FormInstance, FormRules } from 'element-plus'
import { createNews } from '@/api/news'

// 定义emit事件
const emit = defineEmits(['refresh'])

const formRef = ref<FormInstance>()
const drawer2 = ref(false)
const direction = ref<DrawerProps['direction']>('rtl')
const classList = [
  { value: 1, label: '宏观形势', color: '#409EFF' },
  { value: 2, label: '行业动态', color: '#67C23A' },
  { value: 3, label: '产业链动态', color: '#E6A23C' },
  { value: 4, label: '国际能源观察', color: '#F56C6C' },
  { value: 5, label: '其他', color: '#B37FEB' },
]

// 表单验证规则
const rules = ref<FormRules>({
  newsTitle: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
  classReal: [{ required: true, message: '请选择新闻标签', trigger: 'change' }],
  abstractReal: [{ required: true, message: '请输入新闻摘要', trigger: 'blur' }],
})

// 新闻表单数据
const newsForm = ref({
  id: null,
  newsTitle: '',
  classReal: null,
  siteName: '',
  sourceUrl: '',
  abstractReal: '',
  markContent: '',
})

// 关闭前回调
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定要取消添加吗？')
    .then(() => done())
    .catch(() => {})
}

// 取消按钮
const cancelClick = () => {
  ElMessageBox.confirm('确定要取消添加吗？')
    .then(() => {
      drawer2.value = false
    })
    .catch(() => {})
}

// 确定按钮 - 提交表单
const confirmClick = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  // 验证表单
  await formEl.validate((valid) => {
    if (valid) {
      // 显示确认对话框
      ElMessageBox.confirm('确定要提交这条新闻吗？')
        .then(async () => {
          try {
            // 调用API创建新闻
            await createNews({ ...newsForm.value, addMode: 1 }).then((res) => {
              if (res.code === 200) {
                ElMessage.success(res.message || '添加新闻成功')
                // 通知父组件刷新新闻列表
                emit('refresh')
              }
            })
            // 提交后清空表单并关闭抽屉
            resetForm()
            drawer2.value = false
          } catch (error) {
            ElMessage.error('添加新闻失败，请重试')
          }
        })
        .catch(() => {
          // 用户取消提交
        })
    } else {
      // 表单验证失败
      ElMessage.warning('请填写必填项')
    }
  })
}

// 重置表单
const resetForm = () => {
  newsForm.value = {
    id: '',
    newsTitle: '',
    classReal: undefined,
    siteName: '',
    sourceUrl: '',
    abstractReal: '',
    markContent: '',
  }
}

// 暴露方法给父组件使用
defineExpose({
  drawer2,
  resetForm,
})
</script>

<style scoped>
.form-container {
  padding: 20px;
  height: calc(100% - 40px);
  overflow-y: auto;
}

.form-item {
  margin-bottom: 25px;
}

.label {
  display: inline-block;
  width: 100px;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.required {
  color: #ff4d4f;
  margin-right: 4px;
}

.tips {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
  text-align: right;
}

/* 修复抽屉内部滚动问题 */
::v-deep .el-drawer__body {
  padding: 0;
  overflow: hidden;
}
</style>
